package com.demo.service.impl;

import com.demo.dto.Result;
import com.demo.entity.AnswerLike;
import com.demo.entity.UserCollect;
import com.demo.mapper.AnswerLikeMapper;
import com.demo.service.AnswerLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.utils.UserHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class AnswerLikeServiceImpl extends ServiceImpl<AnswerLikeMapper, AnswerLike> implements AnswerLikeService {

    AnswerLike getAnswerLike(Integer answerId, Integer userId) {
        return query().eq("answer_id", answerId).eq("user_id", userId).one();
    }

    @Override
    public Result<AnswerLike> like(Integer answerId) {
        Integer userId = UserHolder.getUser().getUserId();
        // 判断是否已点赞
        AnswerLike answerLike = getAnswerLike(answerId, userId);
        if (getAnswerLike(answerId, userId) != null) {
            // 已点赞，取消点赞
            removeById(answerLike.getId());
            return Result.ok(answerLike, "取消点赞成功");
        }
        else {
            // 未点赞，进行点赞
            AnswerLike answerLikeInsert = new AnswerLike(null, userId, answerId);
            if (!save(answerLikeInsert)) {
                return Result.fail("点赞失败，userId或answerId有误");
            }
            return Result.ok(answerLikeInsert, "点赞成功");
        }
    }
}
